//
//  WDWorderOrderMainVehScanCodeViewController.m
//  wd-serviceapp
//
//  Created by Bin Tang on 2024/9/2.
//

#import "WDWorderOrderMainVehScanCodeViewController.h"
#import "WDWorderOrderMainVehScanCodeViewModel.h"
#import <AVFoundation/AVFoundation.h>
#import "WDScanCodeButton.h"
#import "WDScanCodeBottomView.h"
#import "WDPersonalInfoModifyTipView.h"


@interface WDWorderOrderMainVehScanCodeViewController ()

@property (nonatomic, strong) WDWorderOrderMainVehScanCodeViewModel *viewModel;

@property (nonatomic, strong) UIView *maskView; //蒙版
@property (nonatomic, strong) UIImageView *scanImageView; //扫描边框的背景图片
@property (nonatomic, strong) UIImageView *scanLineImageView; //扫描动画的线条
/// 打开闪光灯
@property (nullable, strong) TYZImageTitleButton *btnTurn;

@property (nonatomic, strong) WDScanCodeBottomView *bottomView;

@property (nonatomic, strong) WDPersonalInfoModifyTipView *modifyTipView;

@end

@implementation WDWorderOrderMainVehScanCodeViewController

- (void)dealloc
{
    debugMethod();
}

- (void)initWithVar
{
    [super initWithVar];
    
    [[WDLocationManager shareInstance] updateLocation];
}

- (void)initWithViewModel {
    _viewModel = [WDWorderOrderMainVehScanCodeViewModel new];
    _viewModel.title = self.scanTitle;
    _viewModel.tipInfo = self.tipInfo;
    _viewModel.serviceModel = self.serviceModel;
    _viewModel.reqModel = self.reqModel;
    
    @weakify(self);
    _viewModel.touchScanCodeResultBlock = ^(NSString * _Nonnull scanCode, NSString * _Nonnull scanType) {
        @strongify(self);
        [self scanCodeResult:scanCode scanType:scanType];
    };
    
    [_viewModel setupData];
}

- (void)initWithNavBar {
    [super initWithNavBar];
    
    [self initWithBackButton];
    
    self.navigationItem.title = self.viewModel.title;
}

- (void)initWithSubView {
    [super initWithSubView];
    
    [self.view addSubview:self.scanImageView];
    [self.view addSubview:self.scanLineImageView];
    [self.view addSubview:self.maskView];
    
    [self initWithBtnTurn];
    
    [self.viewModel setupSession:self];
    @weakify(self);
    [self.viewModel startScan:^{
        @strongify(self);
        [self scanLineAnimation];
    }];
    
    [self initWithBottomView];
    
    [self initWithModifyTipView];
}

- (void)initWithModifyTipView {
    CGRect frame = CGRectMake((kScreenW - 296) * 0.5, (kScreenH - 160) * 0.5 - 30, 296, 160);
    _modifyTipView = [[WDPersonalInfoModifyTipView alloc] initWithFrame:frame];
}


- (UIView *)maskView {
    if (!_maskView) {
        _maskView = [[UIView alloc]initWithFrame:self.view.bounds];
        _maskView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5];
        UIBezierPath *fullBezierPath = [UIBezierPath bezierPathWithRect:self.view.bounds];
        UIBezierPath *scanBezierPath = [UIBezierPath bezierPathWithRect:self.viewModel.scanRect];
        [fullBezierPath appendPath:[scanBezierPath  bezierPathByReversingPath]];
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.path = fullBezierPath.CGPath;
        _maskView.layer.mask = shapeLayer;
    }
    return _maskView;
}

- (UIImageView *)scanImageView {
    if (!_scanImageView) {
        _scanImageView = [[UIImageView alloc] initWithFrame:self.viewModel.scanRect];
        _scanImageView.image = [self.viewModel imageWithName:@"icon_scan_background"];
    }
    return _scanImageView;
}

- (UIImageView *)scanLineImageView {
    if (!_scanLineImageView) {
        CGRect frame = CGRectMake(self.viewModel.scanRect.origin.x,self.viewModel.scanRect.origin.y, self.viewModel.scanRect.size.width, 3);
        _scanLineImageView = [[UIImageView alloc] initWithFrame:frame];
        _scanLineImageView.image = [self.viewModel imageWithName:@"icon_scan_line"];
    }
    return _scanLineImageView;
}

/// 初始化 打开闪光灯按钮
- (void)initWithBtnTurn {
    if (!_btnTurn) {
        UIImage *image = [UIImage imageNamed:@"ic_scan_turn_torch"];
        CGRect frame = CGRectMake((kScreenW - 66) * 0.5, self.scanImageView.bottom - 30 - 52, 66, 52);
        _btnTurn = [TYZImageTitleButton createWithImageButton:self.view frame:frame font:[UIFont systemFontOfSize:12 weight:UIFontWeightLight] target:self action:@selector(actionWithTorch:) propertiesBlock:^(TYZImageTitleButton * _Nonnull button) {
            [button setImage:image forState:UIControlStateNormal];
            [button setTitle:@"轻触照亮" forState:UIControlStateNormal];
            [button setTitle:@"轻触关闭" forState:UIControlStateSelected];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [button layoutButtonWithEdgeInsetsStyle:TYZButtonEdgeInsetsStyleTop imageTitleSpace:8];
        }];
        
    }
}

/// 是否点击闪光灯
/// - Parameter sender: sender description
- (void)actionWithTorch:(id)sender {
    UIButton *btn = (UIButton *)sender;
    btn.selected = !btn.selected;
    [self actionWithTurnTorch: btn.selected];
}

- (void)initWithBottomView {
    if (!_bottomView) {
        CGFloat marginTop = (self.view.frame.size.height - self.viewModel.scanRect.size.height - BootomViewHeight )/2 + self.viewModel.scanRect.size.height;
        float height = kScreenH - marginTop - IPHONEX_BOTTOM_SPACE - NAVBAR_HEIGHT_STATUS;
//        CGRect frame = CGRectMake(0, marginTop, kScreenW, BootomViewHeight);
        CGRect frame = CGRectMake(0, marginTop, kScreenW, height);
        _bottomView = [[WDScanCodeBottomView alloc] initWithFrame:frame];
        [self.view addSubview:_bottomView];
        [_bottomView updateWithViewData:self.viewModel];
        
        @weakify(self);
        // 打开关闭手电筒
        _bottomView.touchTurnTorchBlock = ^(BOOL on) {
            @strongify(self);
            [self actionWithTurnTorch: on];
        };
        
        // 手动输入
        _bottomView.touchInputEventBlock = ^{
            @strongify(self);
            [self actionWithInputEvent];
        };
        
    }
    if (![objectNull(self.viewModel.tipInfo) isEqualToString:@""]) {
        _bottomView.tipInfo = self.viewModel.tipInfo;
    }
}

/// 打开关闭手电筒
/// - Parameter on: on description
- (void)actionWithTurnTorch:(BOOL)on {
    [self.viewModel turnTorch:on];
}

/// 显示手动输入页面
- (void)actionWithInputEvent {
    @weakify(self);
    void(^block)(id data) = ^(NSDictionary *dict) {
        @strongify(self);
        // 1 vin后八位；2 车牌号
//        NSDictionary *dict = @{@"code": str, @"inputType":@(self.viewModel.inputType)};
        NSString *plateNumber = self.viewModel.serviceModel.plateNumber; // 车牌号
        NSString *vin = self.viewModel.serviceModel.vehicleVin;
        NSString *code = dict[@"code"];
        NSInteger inputType = [dict[@"inputType"] integerValue]; // 1 vin后八位；2 车牌号
        if (inputType == 2) { // 车牌号
            if ([plateNumber isEqualToString:code]) { // 输入的车牌号跟工单车牌号一致
                code = self.viewModel.serviceModel.vehicleVin;
            } else {
                [SVProgressHUD showInfoWithStatus:@"您输入的车牌号与工单的不一致！"];
                return;
            }
        } else if (inputType == 1) { // 输入vin码
            NSString *tmpVin = [vin substringFromIndex:vin.length - 8];
            if (code.length == 8 && ![tmpVin isEqualToString:code]) {
                [SVProgressHUD showInfoWithStatus:@"您输入的VIN码与工单的不一致！"];
                return;
            } else if (code.length != 8 && ![vin isEqualToString:code]) {
                [SVProgressHUD showInfoWithStatus:@"您输入的VIN码与工单的不一致！"];
                return;
            }
            code = self.viewModel.serviceModel.vehicleVin;
        }
        [self scanCodeResult:code scanType:nil];
    };
    NSDictionary *params = @{
        @"block": block,
        @"inputType": @(2), // 2 表示车牌号；1 表示vin码
    };
    UIViewController *vc = [[TYZRouter sharedInstance] getInputVinPlateNumberVC:params];
    [TYZJumpVCManager pushBaseVC:self pushVC:vc];
    
    
    
    
//    @weakify(self);
//    void(^block)(id data) = ^(id data) {
//        @strongify(self);
//        [self scanCodeResult:data scanType:nil];
//    };
//    NSDictionary *params = @{
//        @"block": block,
//        @"inputType": @(2), // 2 表示车牌号；1 表示vin码
//    };
//    UIViewController *vc = [[TYZRouter sharedInstance] getInputVinPlateNumberVC:params];
//    [TYZJumpVCManager pushBaseVC:self_weak_ pushVC:vc];
}

#pragma mark - 扫描线动画
//添加扫描线动画
- (void)scanLineAnimation {
    self.scanLineImageView.hidden = NO;
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
    animation.fromValue = @(0);
    animation.toValue = @(self.viewModel.scanRect.size.height - 3);
    animation.duration = 3.0;
    animation.repeatCount = OPEN_MAX;
    animation.fillMode = kCAFillModeForwards;
    animation.removedOnCompletion = NO;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self.scanLineImageView.layer addAnimation:animation forKey:@"scanLineAnimation"];
}

- (void)removeScanLineAnimation {
    [self.scanLineImageView.layer removeAnimationForKey:@"scanLineAnimation"];
    self.scanLineImageView.hidden = YES;
}

/// 扫码结果
/// - Parameters:
///   - scanCode: scanCode description
///   - scanType: scanType description
- (void)scanCodeResult:(NSString *)scanCode scanType:(NSString *)scanType {
    [self removeScanLineAnimation];
    
    @weakify(self);
    // 这里只能扫vin码
//    self.viewModel.reqModel.vehicleVin = scanCode;
    self.viewModel.reqModel.vehicleVin = self.viewModel.serviceModel.vehicleVin;
    [SVProgressHUD showWithStatus:@"提交中......"];
    [self.viewModel requestWithTaskFinishInspect:^(EDSRespondDataEntity * _Nonnull respond) {
        [SVProgressHUD dismiss];
        @strongify(self);
        if (respond.code == EDS_NETWORK_SUCCESS) {
            NSString *tip = objectNull(respond.msg);
            if ([tip isEqualToString:@""]) {
                tip = @"提交成功！";
            }
            [SVProgressHUD showSuccessWithStatus:tip];
            if (self.popResultBlock) {
                self.popResultBlock(scanCode);
            }
//            [self clickedBack:nil];
            [self.navigationController popToRootViewControllerAnimated:YES];
        } else {
            NSString *tip = objectNull(respond.msg);
            if ([tip isEqualToString:@""]) {
                tip = @"您扫描的车辆不是本订单车辆，请重新确认！";
            }
            [SVProgressHUD showInfoWithStatus:tip];
            [self clickedBack:nil];
//            [self errorShowTip:@"您扫描的车辆不是本订单车辆，请重新确认"];
        }
    }];
    
    
//    if ([EDSUtility isValidCarNumber:scanCode]) { // 判断是否是车牌号
//
//    } else { // 不是车牌号
//
//    }
    
    debugLog(@"scanCode=%@", scanCode);
}

/// 错误提示
- (void)errorShowTip:(NSString *)tip {
    @weakify(self);
    NSDictionary *params = @{
        @"desc": tip,
        @"imageTipName": @"ic-error-tip"
    };
    [_modifyTipView showWithTitle:@"提示" data:params completion:^{
        @strongify(self);
        [self.modifyTipView hide];
    } failed:^{
        @strongify(self);
        [self.modifyTipView hide];
        [self clickedBack:nil];
    }];
}
@end
